<template>
  <div class="label-box">
    <slot :name="`label-${control.prop}-front`" />
    <el-tooltip placement="top" :disabled="tooltipDisabled" :content="label">
      <div
        class="label"
        :style="{ width, ...style }"
        @mouseenter="toggleTooltip"
        @mouseleave="toggleTooltip"
      >
        <span :class="['text', { required }]">{{ label }}</span>
        <span class="text-copy">{{ label }}</span>
      </div>
    </el-tooltip>
    <slot :name="`label-${control.prop}-after`" />
  </div>
</template>

<script setup>
const { control, labelWidth, labelStyle } = defineProps(["control", "labelWidth", "labelStyle"]);

const width = computed(() => control.labelWidth || labelWidth || "80px");
const style = computed(() => control.labelStyle || labelStyle || {});
const label = computed(() => control.label);
const required = computed(() => control.required);

const tooltipDisabled = ref(true);
function toggleTooltip({ target }) {
  if (target) {
    const containerWidth = target.clientWidth || 0;
    // 获取text-copy标签
    const targetChild = target.children[1];
    const contentWidth = target?.children.length > 0 ? targetChild.offsetWidth : 0;
    const style = window.getComputedStyle(target) || {};
    const paddingLeft = parseInt(style.paddingLeft);
    const paddingRight = parseInt(style.paddingRight);
    const totalPadding = paddingLeft + paddingRight;
    if (contentWidth > containerWidth - totalPadding) {
      tooltipDisabled.value = false;
    } else {
      tooltipDisabled.value = true;
    }
  }
}
</script>

<style lang="scss" scoped>
.label-box {
  display: flex;
  align-items: center;
  padding-left: 11px;
}
.label {
  position: relative;
  white-space: nowrap;
  padding-right: 4px;
  color: #999999;
  line-height: 1;
}
.text {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  text-transform: capitalize;
}
.required::before {
  content: "*";
  color: red;
  margin-right: 1px;
}
.text-copy {
  position: absolute;
  top: 0;
  z-index: -1;
}
</style>
